package com.magpiebridge.controller;


import com.magpiebridge.pojo.News;

import com.magpiebridge.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@CrossOrigin
public class NewsController {

    @Autowired
    private NewsService newsService;

    @GetMapping("/getAllNews")
    public List<News> getAllNews() {
        return newsService.getAllNews();
    }

    @GetMapping("/getNewsById/{id}")
    public News getNewsById(@PathVariable Integer id) {
        return newsService.getNewsById(id);
    }

    @PostMapping("/insertNews")
    public String insertNews(@RequestBody News news){
        Integer sendid = news.getSendid();
        Integer receptionid = news.getReceptionid();
        String msg = news.getMsg();
        Date sendtime = news.getSendtime();
        String state = news.getState();

        int result = newsService.insertNews(news);
        if (result > 0){
            return "消息发送成功";
        } else {
            return "消息发送失败";
        }
    }

    @DeleteMapping("/deleteNews/{id}")
    public  String deleteNews(@PathVariable  Integer  id)  {
        try  {
            //  查询消息是否存在
            News  news  =  newsService.getNewsById(id);
            if  (news  ==  null)  {
                return  "消息不存在";
            }
            //  撤回消息
            int  result  =  newsService.deleteNews(id);
            if  (result  >  0)  {
                //  更新数据库状态
                return  "消息撤回成功";
            }  else  {
                return  "消息撤回失败";
            }
        }  catch  (Exception  e)  {
            //  记录日志或警告
            //  TODO:  Log  deletion  information
            // 打印错误信息
            System.err.println(e.getMessage());
            return "系统错误";
        }
    }

    @PostMapping("/updateNews/{id}")
    public String updateUser(@PathVariable Integer id, @RequestBody News newNews) {
        try {
            // 查询消息是否存在
            News news = newsService.getNewsById(id);
            if (news == null) {
                return "消息不存在";
            }
            // 更新消息
            news.setSendid(newNews.getSendid());
            news.setReceptionid(newNews.getReceptionid());
            news.setMsg(newNews.getMsg());
            news.setSendtime(newNews.getSendtime());
            news.setState(newNews.getState());

            int result = newsService.updateNews(news);
            if (result > 0) {
                return "消息重新发送成功";
            } else {
                return "消息重新发送失败";
            }
        } catch (Exception e) {
            // 记录日志或警告
            // TODO: Log update information
            // 打印错误信息
            System.err.println(e.getMessage());
            return "系统错误";
        }
    }

}
